//
//  StepRcdViewCtrl.m
//  AccuroFit
//
//  Created by Yongfeng Li on 8/19/15.
//  Copyright (c) 2015 Nci Technology Inc. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "AppDelegate.h"
#import "UIGraphView.h"
#import "StepRcdViewCtrl.h"
#import "P_Steps.h"
#import "UIView+Extension.h"
#define DefaultColor [UIColor colorWithRed:0.00 green:0.53 blue:0.28 alpha:1.00]
@interface StepRcdViewCtrl ()

@end

@implementation StepRcdViewCtrl {
  UILabel* _lblMsg;
  UIGraphView* _gSteps;
  UIGraphView* _gDists;
    
    //UILabel* _lblDatRngTip;
    //UISegmentedControl* _scDateRng;
    
    UIButton* _btnLeft;
    UILabel* _lblWeekBefore;
    UILabel* _lblCurrentWeek;
    UILabel* _lblWeekAfter;
    UIButton* _btnRight;
    
    
    UIView* _ivhLine;
    UIView* _ivvLine;
    
    UILabel* _lblMostStepsTip;
    UILabel* _lblMostDistsTip;
    
    UILabel* _lblMostStepsVal;
    UILabel* _lblMostDistsVal;
    
    NSMutableArray* _pStpData;
    
    NSMutableArray* _values;
    NSDate* _lastDatePos;

    int _nGoalSteps;
    float _fGoalDists;
    
    NSInteger _nDtRngIdx;
    NSDate* _dtFr;
    NSDate* _dtTo;
  
  //sync with svr
  UIButton* _btnSyncData;
  UIProgressView* _progView;
  UIActivityIndicatorView* _actView;
  
  NSURLSession* _netSession;
  //NSMutableDictionary* _dicSyncData;
  
  NSUInteger _nSyncPos;
  NSUInteger _nSyncToatalPack;
  NSUInteger _nSyncCurrentPack;
  
  BOOL _bSyncGetWgtReqst;
  BOOL _bSyncGetNotNeed;
  BOOL _bMadeRcdMark;
  
  NSInteger _nBodyId;
  
  //rember
  CGFloat _yStpDistVal[7];
  NSInteger _nValIdx[7];
  NSDate* _dtMeas;
  
  BOOL _bIpad;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithWhite:0.125 alpha:0.5];
    
    CGRect frame = [[UIScreen mainScreen] bounds];
    CGFloat W = frame.size.width;
    CGFloat H = frame.size.height;
  _bIpad = H > 1000;
  
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //UIImage* imgback = [pApp getImageScale:(_bIpad?@"ic-mainbkgd2@1024.png":@"ic-mainbkgd2.png") scale:(_bIpad?1.0:0.32)];
//  [self.view setBackgroundColor:[UIColor colorWithPatternImage:imgback]];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:self.view.frame];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.image = [UIImage imageNamed:@"ic-mainbkgd2"];
    [self.view insertSubview:imgView atIndex:0];
    CGFloat yPos = (H <= 480)? 60: 65;
    [self initViewCtrls: yPos scrWdt: W scrHgt:H];
  
    //UIImage* iProf = [pApp getImageScale:@"ic-list.png" scale: 0.4];
    //UIBarButtonItem *profButton = [[UIBarButtonItem alloc] initWithImage:iProf style:UIBarButtonItemStylePlain target:self action:@selector(mainAction:)];
    //self.navigationItem.leftBarButtonItem = leftButton;
    //self.navigationItem.rightBarButtonItem = profButton;
  
    //_nGoalSteps = [pApp getBodyGoalStep];
    _nGoalSteps = pApp.m_bodyInfo.nGoalStep;
    _fGoalDists = pApp.m_bodyInfo.fGoalDist;
    
    
    _nDtRngIdx = 0;
    _values = [[NSMutableArray alloc]init];
    [self tapImgBtnView:nil];
    [self setLastStepMeasData];
  
  //sync
  _nBodyId = 0;
  _progView = nil;
  _actView = nil;
  _nSyncPos = 0;
  
  NSURLSessionConfiguration* cnfgSession = [NSURLSessionConfiguration defaultSessionConfiguration];// [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier: @"HrateSync"];
  cnfgSession.timeoutIntervalForRequest = 10.0; 
  _netSession = [NSURLSession sessionWithConfiguration:cnfgSession delegate: self delegateQueue: nil];
  
//  UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//  [btnBack setImage:[UIImage imageNamed:@"btn-left-w.png"] forState:UIControlStateNormal];//@"btn_back.png"
//  [btnBack addTarget:self action:@selector(onRtnMainPage:) forControlEvents:UIControlEventTouchUpInside];
//  
//  UIBarButtonItem* btniBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
//  self.navigationItem.leftBarButtonItem = btniBack;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void) initViewCtrls:(CGFloat) yPos scrWdt:(CGFloat) W scrHgt:(CGFloat)H
{
  BOOL bWider = NO, bIp4s = NO;
  BOOL bIpad = H > 1000;
  BOOL bIp6p = H >= 667;
  if(!bIp6p) {
    bWider = W > 320;
    bIp4s = H <= 480;
  }
    //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    _lblMsg = [[UILabel alloc] initWithFrame:CGRectMake(20, yPos + 5, W-40, 25)];
    _lblMsg.textColor = DefaultColor;
    _lblMsg.font = Regular(15);
    _lblMsg.backgroundColor = [UIColor clearColor];
    _lblMsg.textAlignment = NSTextAlignmentCenter;
    _lblMsg.text = NSLocalizedString(@"Pedometer History", nil);
    [self.view addSubview:_lblMsg];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_lblMsg.frame) + 6, W, 1.0)];
    lineView.backgroundColor = DefaultColor;
    [self.view addSubview:lineView];
    
    //graph
    CGFloat yyPos = yPos + 20 + (bIpad?10:(bWider?5:1));
    CGFloat fGhgt = H / 4 + (bIpad?50:35) - 20;
    CGRect chartFrame  = CGRectMake(5, yyPos, W-10, fGhgt);
    _gSteps = [[UIGraphView alloc] initWithFrame: chartFrame];
    _gSteps.nSetUnit = 253;
    _gSteps.center = CGPointMake(chartFrame.size.width/2.0, chartFrame.size.height/2);
    _gSteps.delegate = self;
    _gSteps.dataSource = self;
    _gSteps.barShadowOffset = CGSizeMake(2.0, 1.0);
    _gSteps.animationDuration = 0.0;
    _gSteps.barShadowColor	 = [UIColor grayColor];
    _gSteps.barShadowAlpha	 = 0.5;
    _gSteps.barShadowRadius = 1.0;
    //_gView.barWidth = (W-10) / 9;//chartFrame.size.width / 10.0;
    _gSteps.xLabelType	 = GraphViewXLabelTypeHorizontal;
    //_gView.incrementValue = 50;
    _gSteps.barTextType = GraphViewBarTextTypeTop;
    _gSteps.barTextColor = [UIColor whiteColor];
    _gSteps.gridColor = DefaultColor;
//    _gSteps.backgroundColor = [UIColor yellowColor];
    _gSteps.frame = chartFrame;
    [self.view addSubview:_gSteps];

    /*yyPos = _gDists.frame.origin.y + _gDists.frame.size.height + 10;
    _lblSystolicTag = [[UILabel alloc] initWithFrame:CGRectMake(W/12, yyPos, W/3, 25)];
    _lblSystolicTag.textColor = [UIColor blueColor];
    _lblSystolicTag.font = [UIFont fontWithName:@"Calibri" size:16.0];
    _lblSystolicTag.backgroundColor = [UIColor clearColor];
    _lblSystolicTag.textAlignment = NSTextAlignmentCenter;
    _lblSystolicTag.text = @"____ Systolic";
    [self.view addSubview:_lblSystolicTag];
    
    _lblDiastolicTag = [[UILabel alloc] initWithFrame:CGRectMake(W* 7 / 12, yyPos, W/3, 25)];
    _lblDiastolicTag.textColor = [UIColor redColor];
    _lblDiastolicTag.font = [UIFont fontWithName:@"Calibri" size:16.0];
    _lblDiastolicTag.backgroundColor = [UIColor clearColor];
    _lblDiastolicTag.textAlignment = NSTextAlignmentCenter;
    _lblDiastolicTag.text = @"____ Diastolic";
    [self.view addSubview:_lblDiastolicTag];*/
    
    //date rng
  CGFloat xPos = bIpad? 45: bIp6p?20: bWider? 12:5;
  yyPos = _gSteps.frame.origin.y + _gSteps.frame.size.height - (bIpad?0:bIp6p?-15:10);
    CGFloat fSize = bIpad? 48: bWider? 36:36;
    
    //UIImage* iBtn = [pApp getImageScale: @"btn-left.png" scale:(1.0)];
    UIImage* iBtn = [UIImage imageNamed:@"btn-left.png"];
    _btnLeft = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnLeft.frame = CGRectMake(xPos, yyPos, fSize, fSize);
    [_btnLeft setBackgroundImage:[UIImage imageNamed:@"btn-left-s.png"] forState:UIControlStateNormal];
    [_btnLeft setBackgroundImage:[UIImage imageNamed:@"btn-left-s.png"] forState:UIControlStateSelected];
    [_btnLeft addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnLeft];

    iBtn = [UIImage imageNamed: @"btn-right.png"];
    _btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    _btnRight.frame = CGRectMake(W-xPos-fSize, yyPos, fSize, fSize);
    [_btnRight setBackgroundImage:[UIImage imageNamed:@"btn-right-s.png"] forState:UIControlStateNormal];
    [_btnRight setBackgroundImage:[UIImage imageNamed:@"btn-right-s.png"] forState:UIControlStateSelected];
    [_btnRight addTarget:self action:@selector(tapImgBtnView:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_btnRight];

    CGFloat fxDelta = (W - (xPos + fSize) * 2) / 3.0;
    xPos += fSize;
    _lblWeekBefore = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos+fSize/4, fxDelta, 25)];
    _lblWeekBefore.textColor = [UIColor blackColor];
    _lblWeekBefore.font = Regular(11);
    _lblWeekBefore.backgroundColor = [UIColor clearColor];
    _lblWeekBefore.textAlignment = NSTextAlignmentCenter;
    _lblWeekBefore.text = NSLocalizedString(@"Week Before", nil);
    [self.view addSubview:_lblWeekBefore];
    
    xPos += fxDelta;
    _lblCurrentWeek = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos+fSize/4, fxDelta, 25)];
    _lblCurrentWeek.textColor = [UIColor blackColor];
    _lblCurrentWeek.font = Regular(11);
    _lblCurrentWeek.backgroundColor = [UIColor clearColor];
    _lblCurrentWeek.textAlignment = NSTextAlignmentCenter;
    _lblCurrentWeek.text = NSLocalizedString(@"Current Week", nil);
    [self.view addSubview:_lblCurrentWeek];

    xPos += fxDelta;
    _lblWeekAfter = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yyPos+fSize/4, fxDelta, 25)];
    _lblWeekAfter.textColor = [UIColor blackColor];
    _lblWeekAfter.font = Regular(11);
    _lblWeekAfter.backgroundColor = [UIColor clearColor];
    _lblWeekAfter.textAlignment = NSTextAlignmentCenter;
    _lblWeekAfter.text = NSLocalizedString(@"Week After", nil);
    [self.view addSubview:_lblWeekAfter];

    
    UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_lblWeekAfter.frame) + 16, W, 1.0)];
    lineV.backgroundColor = DefaultColor;
    [self.view addSubview:lineV];
    /*_lblDatRngTip = [[UILabel alloc] initWithFrame:CGRectMake(5, yyPos, xPos - 5, 30)];
    _lblDatRngTip.textColor = [UIColor lightGrayColor];
    _lblDatRngTip.font = [UIFont systemFontOfSize:bIpad?20:(bWider?16:12)];
    _lblDatRngTip.backgroundColor = [UIColor clearColor];
    _lblDatRngTip.textAlignment = NSTextAlignmentCenter;
    _lblDatRngTip.text = @"Timeline:";
    [self.view addSubview:_lblDatRngTip];
    
    _scDateRng = [[UISegmentedControl alloc]initWithFrame:CGRectMake(xPos, yyPos, W-xPos-10, 30)];
    //UIColor* bgColor = [UIColor colorWithRed:0.98 green:0.45 blue:0.05 alpha:0.25];
    //_scDateRng. = bgColor;
    //_scDateRng.tintColor = [UIColor lightGrayColor];
    _scDateRng.tintColor = [UIColor clearColor];
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: [UIColor orangeColor]};
    [_scDateRng setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16], NSForegroundColorAttributeName: [UIColor lightTextColor]};
    [_scDateRng setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    
    [_scDateRng insertSegmentWithTitle:@"All" atIndex:0 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"1 W" atIndex:1 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"1 M" atIndex:2 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"3 M" atIndex:3 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"6 M" atIndex:4 animated:NO];
    [_scDateRng insertSegmentWithTitle:@"1 Y" atIndex:5 animated:NO];
    _scDateRng.selectedSegmentIndex = 3;
    [_scDateRng addTarget: self action:@selector(chgDateRng:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_scDateRng];*/
    
    chartFrame.origin.y += H / 4 + fSize * (bIpad?3:2) - 30;
    if(H == 480)
        chartFrame.origin.y -= 42;
    _gDists = [[UIGraphView alloc] initWithFrame: CGRectMake(0, CGRectGetMaxY(_btnLeft.frame), self.view.frame.size.width - 10, chartFrame.size.height)];
    _gDists.nSetUnit = 254;
//    _gDists.center = CGPointMake(chartFrame.size.width/2.0, chartFrame.size.height/2);
    _gDists.delegate = self;
    _gDists.dataSource = self;
    _gDists.barShadowOffset = CGSizeMake(2.0, 1.0);
    _gDists.animationDuration = 0.0;
    _gDists.barShadowColor	 = [UIColor grayColor];
    _gDists.barShadowAlpha	 = 0.5;
    _gDists.barShadowRadius = 1.0;
    //_gView.barWidth = (W-10) / 9;//chartFrame.size.width / 10.0;
    _gDists.xLabelType	 = GraphViewXLabelTypeHorizontal;
    //_gView.incrementValue = 50;
    _gDists.barTextType = GraphViewBarTextTypeTop;
    _gDists.barTextColor = [UIColor whiteColor];
    _gDists.gridColor = DefaultColor;
    //_gView.backgroundColor = [UIColor grayColor];
//    _gDists.centerX = _gSteps.centerX;
    [self.view addSubview:_gDists];
    
//    _gDists.backgroundColor = [UIColor redColor];
  //sync
  xPos = W - (bIpad?82:(bIp4s?58:66));
  yyPos =  H * 2 / 3 + (bIpad?10:(bIp4s?0:5)) + 30;
  iBtn = [[UIImage imageNamed:@"btn-sync-gr.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  _btnSyncData = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnSyncData.frame = CGRectMake(xPos, CGRectGetMaxY(_gDists.frame) - 5, 40, 40);
  [_btnSyncData setBackgroundImage:iBtn forState:UIControlStateNormal];
  [_btnSyncData addTarget:self action:@selector(tapStartSync:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:_btnSyncData];
    
    //line
    //yyPos = chartFrame.origin.y + chartFrame.size.height;
    //yyPos += bIpad?80:(bWider?50:(bIp4s?30:40));
    yyPos = H - (bIpad?220:(bWider?130:(bIp4s?100:100)));
    CGRect rt;
    UIImage* iConh = [[UIImage imageNamed:@"ic-horline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    CGFloat fHgt = W * iConh.size.height / iConh.size.width;
    rt.origin.x = 0;
    rt.origin.y = yyPos;//(H / 2.0) + (bIpad? 115: (bIp4s?40:(bWider?85:65)));
    rt.size.height = fHgt;
    rt.size.width = W;
    rt.size.height = 1.0;
    _ivhLine  = [[UIView alloc] initWithFrame:rt];
    _ivhLine.backgroundColor = [UIColor grayColor];
    _ivhLine.alpha = 0.7;
//    [_ivhLine setImage:iConh];
    [self.view addSubview:_ivhLine];
    
    yyPos += bIpad?20:(bWider?15:(bIp4s?10:10));
    //UIImage* iConv = [[UIImage imageNamed:@"ic-verline.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    rt.origin.x = W / 2.0 - fHgt / 2.0;
    rt.size.height = H -  rt.origin.y - rt.size.height - (bIpad?20:10);
    rt.size.width = fHgt;//iCon.size.width;
    rt.origin.y = rt.origin.y + (bIpad?15:(bWider?10:(bIp4s?5:7)));
    _ivvLine  = [[UIView alloc] initWithFrame:CGRectMake( W / 2, CGRectGetMaxY(_ivhLine.frame), CGRectGetHeight(_ivhLine.frame), 500)];
    _ivvLine.backgroundColor = [UIColor grayColor];
    _ivvLine.alpha = 0.7;
//    [_ivvLine setImage:iConv];
    [self.view addSubview:_ivvLine];
    //bld tips and values
    //yyPos = rt.origin.y + (bIpad?40:(bWider?10:(bIp4s?0:5)));
    yyPos -= 5;//H - (bIpad?100:(bWider?100:(bIp4s?80:80)));
    _lblMostStepsVal = [[UILabel alloc] initWithFrame:CGRectMake(0, yyPos, W / 2, 50)];
    _lblMostStepsVal.textColor = DefaultColor;
    _lblMostStepsVal.font = Bold(36);
    _lblMostStepsVal.backgroundColor = [UIColor clearColor];
    _lblMostStepsVal.textAlignment = NSTextAlignmentCenter;
    _lblMostStepsVal.text = @"118";
    [self.view addSubview:_lblMostStepsVal];
    
    _lblMostDistsVal = [[UILabel alloc] initWithFrame:CGRectMake(W / 2, yyPos, W / 2, 50)];
    _lblMostDistsVal.textColor = DefaultColor;
    _lblMostDistsVal.font = Bold(36);
    _lblMostDistsVal.backgroundColor = [UIColor clearColor];
    _lblMostDistsVal.textAlignment = NSTextAlignmentCenter;
    _lblMostDistsVal.text = @"76";
    [self.view addSubview:_lblMostDistsVal];
//    _lblMostStepsTip = [[UILabel alloc] initWithFrame:CGRectMake(0, yyPos, W / 2, 50)];
    
    yyPos += bIpad?70:(bWider?55:(bIp4s?35:50));
    _lblMostStepsTip = [[UILabel alloc] initWithFrame:CGRectMake(0, yyPos, W / 2, 50)];
    _lblMostStepsTip.textColor = [UIColor blackColor];
    _lblMostStepsTip.font = Semibold(15);
    _lblMostStepsTip.backgroundColor = [UIColor clearColor];
    _lblMostStepsTip.textAlignment = NSTextAlignmentCenter;
    _lblMostStepsTip.lineBreakMode = NSLineBreakByWordWrapping;
    _lblMostStepsTip.numberOfLines = 0;
    _lblMostStepsTip.text = NSLocalizedString(@"Most steps\nin one day", nil);
    [self.view addSubview:_lblMostStepsTip];
    
    _lblMostDistsTip = [[UILabel alloc] initWithFrame:CGRectMake(W / 2, yyPos, W / 2, 50)];
    _lblMostDistsTip.textColor = [UIColor blackColor];
    _lblMostDistsTip.font = Semibold(15);
    _lblMostDistsTip.backgroundColor = [UIColor clearColor];
    _lblMostDistsTip.textAlignment = NSTextAlignmentCenter;
    _lblMostDistsTip.lineBreakMode = NSLineBreakByWordWrapping;
    _lblMostDistsTip.numberOfLines = 0;
    _lblMostDistsTip.text = NSLocalizedString(@"Most distance\nin one day", nil);
    [self.view addSubview:_lblMostDistsTip];
}

- (void)didReceiveMemoryWarning {
  [super didReceiveMemoryWarning];
  // Dispose of any resources that can be recreated.
  _lblMsg.text = NSLocalizedString(@"No enough memory!", nil);
  AudioServicesPlaySystemSound(1112);
}

- (void) viewWillDisappear:(BOOL)animated
{
  [_netSession invalidateAndCancel];
}

- (void) setLastStepMeasData
{
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    int nSteps = 0;
    float fDists = 0.0;
    
    NSMutableArray* pData = [NSMutableArray arrayWithArray:[pApp loadStepsData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:NO last:YES]];
    if(pData != nil && pData.count > 0) {
        P_Steps* pStep = (P_Steps*)[pData objectAtIndex:0];
        if(pStep != nil) {
            nSteps = pStep.nSteps.intValue;
        }
    }
    
    pData = [NSMutableArray arrayWithArray:[pApp loadStepsData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:YES]];
    if(pData != nil && pData.count > 0) {
        P_Steps* pStep = (P_Steps*)[pData objectAtIndex:0];
        if(pStep != nil) {
            //NSDate* dtMeas = pStep.measDate;
            //if([pApp dateIsToday: dtMeas])
                fDists = pStep.tDistances.floatValue;
        }
    }
    
    _lblMostStepsVal.text = (nSteps>0)?[NSString stringWithFormat:@"%d", nSteps]: @"----";
    _lblMostDistsVal.text = (fDists>0)?[NSString stringWithFormat:@"%.1f mi", fDists]: @"----";
}

-(void)mainAction:(id)sender  
{  
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp enterPageWithRes:@"bodyProfViewCtrl"];
}

- (NSTimeInterval) getTimeOffset:(NSInteger)nRngIdx
{
    NSTimeInterval dtInterval = _OneDaySeconds;
    dtInterval = dtInterval * 6.0  +  dtInterval * nRngIdx * 7;
    /*else if(nRngIdx == 2)
        dtInterval *= 30;
    else if(nRngIdx == 3)
        dtInterval *= 90;
    else if(nRngIdx == 4)
        dtInterval *= 180;
    else if(nRngIdx == 5)
        dtInterval *= 365;*/
    dtInterval = -dtInterval;
    
    return dtInterval;
}

-(void) tapImgBtnView:(id)sender
{
  if(_pStpData != nil)
    [_pStpData removeAllObjects];
  
  if(sender == _btnLeft) {
    _nDtRngIdx++;
    _btnLeft.selected = YES;
    _btnRight.selected = NO;
  }
  else if(sender == _btnRight) {
    _nDtRngIdx--;
      
    _btnRight.selected = YES;
    _btnLeft.selected = NO;
  }
 
  //date rng
  NSTimeInterval dtInterval = [self getTimeOffset:_nDtRngIdx];
  
  NSCalendar *calendar = [NSCalendar currentCalendar];
  calendar.timeZone = [NSTimeZone localTimeZone];//[NSTimeZone timeZoneWithName:@"UTC"];
  NSDate *midnight = [calendar dateBySettingHour:0 minute:0 second:0 ofDate:[NSDate date] options:0];
  
  _dtFr = [midnight dateByAddingTimeInterval:(dtInterval+1)];
  //_dtTo = [midnight dateByAddingTimeInterval:_OneDaySeconds-1];
  _dtTo = [_dtFr dateByAddingTimeInterval:(7 * _OneDaySeconds-2)];
    
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //NSString* sFr = [pApp.dtFmt stringFromDate:dtFr];
  //NSString* sTo = [pApp.dtFmt stringFromDate:dtTo];
    
  _pStpData = [NSMutableArray arrayWithArray:[pApp loadStepsData:pApp.m_bodyInfo.m_nBodyId from:_dtFr to:_dtTo sort:YES last:NO]];
  [self showStpData:_pStpData];
  AudioServicesPlaySystemSound(1109);
}

- (void) showStpData:(NSMutableArray*)pStpDate
{
    //NSUInteger nCount = pStpDate.count;
    [_gSteps reloadDataWithColor:[UIColor blackColor]];
    [_gDists reloadDataWithColor:[UIColor blackColor]];
}

//datasource and delegate
- (UIColor *)barChartColor
{
    return [UIColor colorWithWhite:0.75 alpha:0.75];
}

- (NSUInteger)numberOfBarsInBarChart:(UIGraphView *)barChart
{
    return 7;
    /*if(_values != nil)
        return _values.count;
    else
        return 0;*/
}


- (CGFloat)barChart:(UIGraphView *)barChart valueForBarAtIndex:(NSUInteger)index
{
  NSUInteger nCount = _pStpData.count;
  if(_pStpData == nil || nCount == 0)
    return 0.0f;
  
  if(index == 0) {
    for(int n=0; n<7; n++) {
      _nValIdx[n] = -1;
      _yStpDistVal[n] = 0.0;
    }
    
    if(_pStpData.count > 0) {
      P_Steps* nStpData = (P_Steps *)[_pStpData objectAtIndex:0];
      _dtMeas = nStpData.measDate;
    }
    else {
      _dtMeas = [NSDate date];
    }
  }
    
  NSInteger nIdx = -1;
  CGFloat fSteps = 0.0;
  if(_pStpData == nil || nCount <= index || _nValIdx[index] == index) {
    if(_nValIdx[index] == index)
      fSteps = _yStpDistVal[index];
    return fSteps;
  }
  
  for(int n=0; n<7; n++) {
    _nValIdx[n] = -1;
    _yStpDistVal[n] = 0.0;
  }
  for(NSUInteger i=0; i<nCount; i++) {
    P_Steps* nStpData = (P_Steps *)[_pStpData objectAtIndex:i];
    if(nStpData != nil) {
      NSCalendar* calDate = [NSCalendar currentCalendar];
      NSInteger nSteps = nStpData.nSteps.integerValue;
      NSDate* dtMeas = nStpData.measDate;
      double fDelta = [dtMeas timeIntervalSinceDate:_dtFr];
      int nScds = _OneDaySeconds;
      nIdx = (NSInteger)(fDelta / nScds + 0.5) - 1;
      if(nIdx < 0)
        nIdx = 0;
      else if(nIdx > 6)
        nIdx = 6;
      
      //nIdx = 5;
      BOOL bSameDay = [calDate isDate:dtMeas inSameDayAsDate:_dtMeas];
      if(nSteps > 0 && bSameDay)
        _yStpDistVal[nIdx] += nSteps;
      else
        _yStpDistVal[nIdx] = nSteps;
      
      
      _nValIdx[nIdx] = nIdx;
      _dtMeas = dtMeas;
    }
  }
  
  if(_nValIdx[index] == index) {
    fSteps = _yStpDistVal[index];
  }

  return fSteps;
}

- (CGFloat)barChart:(UIGraphView *)barChart distanceAtIndex:(NSUInteger)index
{
  NSUInteger nCount = _pStpData.count;
  if(_pStpData == nil || nCount == 0)
    return 0.0f;
  
  if(index == 0) {
    for(int n=0; n<7; n++) {
      _nValIdx[n] = -1;
      _yStpDistVal[n] = 0.0;
    }
    
    if(_pStpData.count > 0) {
      P_Steps* nStpData = (P_Steps *)[_pStpData objectAtIndex:0];
      _dtMeas = nStpData.measDate;
    }
    else {
      _dtMeas = [NSDate date];
    }
  }
    
  CGFloat fDists = 0.0;
  if(_pStpData == nil || nCount <= index || _nValIdx[index] == index) {
    if(_nValIdx[index] == index)
      fDists = _yStpDistVal[index];
    return fDists;
  }
  
  for(int n=0; n<7; n++) {
    _nValIdx[n] = -1;
    _yStpDistVal[n] = 0.0;
  }
  for(NSUInteger i=0; i<nCount; i++ ) {
    P_Steps* nStpData = (P_Steps *)[_pStpData objectAtIndex:i];
    if(nStpData != nil) {
      NSCalendar* calDate = [NSCalendar currentCalendar];
      float fDistnce = nStpData.tDistances.floatValue;// / 1000.0;
      NSDate* dtMeas = nStpData.measDate;
      double fDelta = [dtMeas timeIntervalSinceDate:_dtFr];
      int nScds = _OneDaySeconds;
      NSInteger nIdx = (NSInteger)(fDelta / nScds + 0.5) - 1;
      if(nIdx < 0)
        nIdx = 0;
      else if(nIdx > 6)
        nIdx = 6;
      
      BOOL bSameDay = [calDate isDate:dtMeas inSameDayAsDate:_dtMeas];
      AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
      if (pApp.m_bodyInfo.nHgtUn == 2) {
        fDistnce *= _KmtoMis;
      }
      if(fDistnce > 0 && bSameDay)
        _yStpDistVal[nIdx] += fDistnce;
      else
        _yStpDistVal[nIdx] = fDistnce;

      
      _nValIdx[nIdx] = nIdx;
      _dtMeas = dtMeas;
    }
  }
  
  if(_nValIdx[index] == index) {
    fDists = _yStpDistVal[index];
  }
  
  return fDists;
}


- (CGFloat)barChart:(UIGraphView *)barChart xposForBarAtIndex:(NSUInteger)index
{
    //return index * 5.5;
    
    if(_pStpData == nil)
        return 0.0;
    
    NSUInteger nIdx = index;
    NSUInteger nCount = _pStpData.count;
    if(nIdx-1 >= nCount)
        nIdx = nCount - 1;
    
    P_Steps* pStpObj = [_pStpData objectAtIndex:nIdx]; 
    NSDate* dtMeas = [pStpObj.measDate initWithTimeInterval:0 sinceDate:_dtFr];
    
    CGFloat xPos = [dtMeas timeIntervalSince1970];
    return xPos;
}

- (NSString *)barChart:(UIGraphView *)barChart xLabelForBarAtIndex:(NSUInteger)index
{
    //NSString* sDate = [NSString stringWithFormat:@"09/%02i", (int)index];
    //return sDate;
    
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSString* sInitDtFmt = pApp.dtFmt.dateFormat;
    NSDateFormatter* _dtFmt = pApp.dtFmt;
    [_dtFmt setDateFormat:@"MM/dd"];
    
    NSString* sDate = @"00/00";
    //if(_pStpData == nil || index < _pStpData.count) {
        NSDate* dtDay = [_dtFr dateByAddingTimeInterval:_OneDaySeconds * index];
        sDate = [_dtFmt stringFromDate: dtDay];
    //}
    
    /*P_Steps* nStpData = (P_Steps *)[_pStpData objectAtIndex:index];
    if(nStpData != nil) {
        sDate = [_dtFmt stringFromDate: nStpData.measDate];
    }*/
    [pApp.dtFmt setDateFormat:sInitDtFmt];
    return sDate;
}

- (NSString *)barChart:(UIGraphView *)barChart textForBarAtIndex:(NSUInteger)index
{
    /*float fVal = [self barChart: barChart valueForBarAtIndex:index] / 1000.0;
    NSString* sFmt =  (fVal > 0.1)?@"%.2f":@"%.3f";
    if(fVal < 0.001)
        sFmt = @"%.4f";
    else if(fVal < 0.01)
        sFmt = @"%.3f";*/
     float fVal = [self barChart: barChart valueForBarAtIndex:index];
     NSString* sFmt =  @"%.0f";
     if(fVal < 1)
     sFmt = @"%.4f";
     else if(fVal < 10)
     sFmt = @"%.3f";
  

    return [NSString stringWithFormat:sFmt, fVal];
    
    /*if(_values == nil || _values.count == 0)
        return @"0";
    
    BdpMeasData *nBdpData = (BdpMeasData *)[_values objectAtIndex:index];
    short nBdpHval = nBdpData.nBphVal;
    NSString* sVal = [NSString stringWithFormat:@"%i", nBdpHval];
    return sVal;*/
}

- (NSString*)barChart:(UIGraphView *)barChart distTxtForBarAtIndex:(NSUInteger)index
{
    float fVal = [self barChart: barChart distanceAtIndex:index];
    /*AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (pApp.m_bodyInfo.nHgtUn == 2) {
        fVal *= _KmtoMis;
    }*/
    NSString* sFmt = (fVal > 0.1)?@"%.1f":@"%.2f";
    if(fVal < 0.001)
        sFmt = @"%.5f";
    else if(fVal < 0.01)
        sFmt = @"%.3f";
    return [NSString stringWithFormat:sFmt, fVal];
}

//ble
- (UIColor *)barChart:(UIGraphView *)barChart colorForBarAtIndex:(NSUInteger)index
{
    return [UIColor colorWithWhite:0.5 alpha:0.5];
}

/*- (short)barChart:(UIGraphView *)barChart lPresForBarAtIndex:(NSUInteger)index
{
    return index * 15;
}

- (short)barChart:(UIGraphView *)barChart hRateForBarAtIndex:(NSUInteger)index
{
    return 25;//index * 20;
}*/

- (int)goalSteps
{
  //return _nGoalSteps;
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
  return pApp.m_bodyInfo.nGoalStep;
}

- (float) goalDists
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
  
  float fGoalDists =  pApp.m_bodyInfo.fGoalDist;
    

  /*fGoalDists = fGoalDists / 100.0 / 1000.0;
  if (pApp.m_bodyInfo.nHgtUn == 2) {
      fGoalDists *= _KmtoMis;
  }*/
        
  return fGoalDists;
}

//sync with svr
- (void) tapStartSync:(id)sender
{
  AppDelegate* pApp = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  if(![pApp isNetWorkConnAvailable]) {
    _lblMsg.text = NSLocalizedString(@"WAN network is not Aviable!", nil);
    _lblMsg.textColor = [UIColor redColor];
    AudioServicesPlaySystemSound(1112);
    return;
  }

  
  _lblMsg.text = NSLocalizedString(@"Begin Sync Data", nil);  //_bMadeRcdMark = NO;
  _nSyncPos = 0;
  NSInteger nBodyId = pApp.m_bodyInfo.m_nBodyId;
  _nBodyId = nBodyId;
  
  //form exists data
  _pStpData = [NSMutableArray arrayWithArray:[pApp loadStepsData:pApp.m_bodyInfo.m_nBodyId from:nil to:nil sort:YES last:NO]];
  NSUInteger nCount = _pStpData.count;
  //[_dicSyncData removeAllObjects];
  
  NSString* sExistIds = @"(";
  for(NSUInteger i=0; i<nCount; i++) {
    P_Steps* pData = [_pStpData objectAtIndex:i];
    NSString* sKey = pData.measId.stringValue;
    
    BOOL bALreadyInc = [sExistIds rangeOfString:sKey].location != NSNotFound;
    if(sKey.integerValue < 0 || bALreadyInc)
      continue;
    
    if(sExistIds.length > 1)
      sExistIds = [sExistIds stringByAppendingFormat:@",%@", sKey];
    else
      sExistIds = [sExistIds stringByAppendingFormat:@"%@", sKey];
  }
  sExistIds = [sExistIds stringByAppendingString:@")"];
  
  if(_progView == nil) {
    //CGRect frame = [[UIScreen mainScreen] bounds];
    //CGFloat W = frame.size.width;
    
    CGRect rt = _btnSyncData.frame;
    CGFloat yPos = rt.origin.y + 25;
    _progView = [[UIProgressView alloc] initWithFrame:CGRectMake(20, yPos, rt.origin.x-20, 10)];
    [self.view addSubview:_progView];
  }
  _progView.hidden = NO;
  _progView.progress = 0.0;
  
  if(_actView == nil) {
    CGRect rt = _btnSyncData.frame;
    _actView = [[UIActivityIndicatorView alloc] initWithFrame:rt];
    _actView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    _actView.hidesWhenStopped = YES;
    [self.view addSubview:_actView];
  }
  _btnSyncData.hidden = YES;
  //[NSThread detachNewThreadSelector:@selector(startActIndicator) toTarget:self withObject:nil];
  [_actView startAnimating];
  
  
  [self getStpDataInfo:sExistIds];
}


-(void) getStpDataInfo:(NSString*)sExistIds
{
  _lblMsg.text = NSLocalizedString(@"Sync Pedo Step Data...", nil);
  _nSyncPos = 0;
  _nSyncCurrentPack = 0;
  _nSyncToatalPack = 0;
  _bSyncGetWgtReqst = YES;
  
  NSString* sUrl = [NSString stringWithFormat:@"Stp?id=%ld&exist=%@&idx=%@" , (long)_nBodyId, sExistIds, @"1"];
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"DELETE" url:sUrl data:nil];
  request.timeoutInterval = 10.0;
  [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if(data == nil)
      return;
    
    // handle response
    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    if(sRecv.length > 10) {
      [self stopSyncProcess];
      return;
    }
    else if(sRecv.length == 0) {
      _lblMsg.text = NSLocalizedString(@"APP Server can not connected!", nil);
      _lblMsg.textColor = [UIColor redColor];
      
      _nSyncToatalPack = -1;
      [self stopShowSyncCtrld];
      AudioServicesPlaySystemSound(1112);
      return;
    }
    
    _nSyncToatalPack = sRecv.integerValue;
    if(_nSyncToatalPack > 0) {
      _bSyncGetNotNeed = NO;
      [self requestStpData];
      //[self syncSendHrateData];
    }
    else {
      //_lblMsg.text = @"Not need SYNC with Download";
      //[self performSelectorOnMainThread:@selector(noSyncDownloadTip:) withObject:@"Not need SYNC with Download" waitUntilDone:NO];
      //[NSThread sleepForTimeInterval:1.0];
      _bSyncGetNotNeed = YES;
      [self stopSyncProcess];
    }
  }];
  
  /*NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
   [task resume];*/
}

- (void) stopSyncProcess
{
  //_scDateRng.selectedSegmentIndex = 0;
  
  dispatch_async(dispatch_get_main_queue(), ^{
    [_netSession finishTasksAndInvalidate];
    
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    NSTimeInterval dtInterval = [self getTimeOffset:_nDtRngIdx];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.timeZone = [NSTimeZone localTimeZone];//[NSTimeZone timeZoneWithName:@"UTC"];
    NSDate *midnight = [calendar dateBySettingHour:0 minute:0 second:0 ofDate:[NSDate date] options:0];
    
    _dtFr = [midnight dateByAddingTimeInterval:(dtInterval+1)];
    _dtTo = [_dtFr dateByAddingTimeInterval:(7 * _OneDaySeconds-2)];
    
    //_pStpData = [NSMutableArray arrayWithArray:[pApp loadStepsData:pApp.m_bodyInfo.m_nBodyId from:_dtFr to:_dtTo sort:YES last:NO]];
    _pStpData = [NSMutableArray arrayWithArray:[pApp loadStepsData:pApp.m_bodyInfo.m_nBodyId from:_dtFr to:_dtTo sort:YES last:NO]];
    //NSUInteger n = _pStpData.count;
    //int m = 0;
    
    [self stopShowSyncCtrld];
  });
  //[self performSelector:@selector(stopShowSyncCtrld) withObject:nil afterDelay:0.05]
}

-(void) stopShowSyncCtrld
{  
  //dispatch_sync(dispatch_get_main_queue(), ^{
  NSString* sMsg = NSLocalizedString(@"SYNC completed!", nil);
  if(_bSyncGetNotNeed)
    sMsg = NSLocalizedString(@"Step Data Already SYNC!", nil);
  
  //dispatch_async(dispatch_get_main_queue(), ^{
  
  // computations 
  [_actView performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
  //[_actView stopAnimating];
  
  _btnSyncData.hidden = NO;
  if(_progView != nil)
    _progView.hidden = YES;
  
  _lblMsg.text = sMsg;
  //[_lblMsg performSelectorOnMainThread:@selector(setText:) withObject:sMsg waitUntilDone:YES];
  
  [self showStpData:_pStpData];
  
  if(_bSyncGetNotNeed)
    AudioServicesPlaySystemSound(1112);
  //});
}

- (void) requestStpData {
  if(_nSyncPos >= _nSyncToatalPack) {
    _nSyncPos = 0;
    [self stopSyncProcess];
    return;
  }
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSString* sUrl = [NSString stringWithFormat:@"Stp?id=%ld", (long)_nBodyId];
  NSDictionary *measData = @{
                             @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nBodyId],
                             @"hType" : [NSString stringWithFormat:@"1"],
                             @"_nSyncPos" : [NSString stringWithFormat:@"%ld", (long)_nSyncPos]
                             };
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measData];
  request.timeoutInterval = 10.0;
  
  
  // 6.发送连接请求
  //[NSURLConnection connectionWithRequest:request delegate:self];
  NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
  [task resume];
}


- (void) showSyncProgress
{
  if(_nSyncToatalPack > 0) {
    if(_nSyncCurrentPack >= _nSyncToatalPack)
      _lblMsg.text = NSLocalizedString(@"Wait...", nil);
    else
      _lblMsg.text = [NSString stringWithFormat:@"SYNC %ld / %ld with %@...", (long)(_nSyncCurrentPack+1), (long)_nSyncToatalPack, (_bSyncGetWgtReqst?NSLocalizedString(@"Download Step", nil):@"")]; //(long)(_nSyncPos+1)];
    CGFloat fProg = (CGFloat)(_nSyncCurrentPack+1) / _nSyncToatalPack;
    _progView.progress = fProg;
  }
}

- (void) storeSyncGetStpData:(NSData*)wData
{
  if(_nSyncPos >= _nSyncToatalPack) {
    _nSyncPos = 0;
    [self stopSyncProcess];
    return;
  }
  [self performSelectorOnMainThread:@selector(showSyncProgress) withObject:nil waitUntilDone:NO];
  
  //NSString* sRecv = [[NSString alloc] initWithData:hData encoding:NSASCIIStringEncoding];
  
  NSError *e = nil;
  NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: wData options: NSJSONReadingMutableContainers error: &e];;
  for(NSDictionary *item in jsonArray) {
    //NSLog(@"Item: %@", item);
    NSNumber* nMeasId = [item objectForKey: @"MeasId"];
    NSString* sDate = [item objectForKey:@"MeasTime"];
    
    NSNumber* nSteps = [item objectForKey:@"Steps"];
    NSNumber* nDista = [item objectForKey:@"Dists"];
    NSNumber* nCalory = [item objectForKey:@"StepCalory"];
    
    [self storeSyncDownloadStpData:nMeasId date:sDate step:nSteps dist:nDista calory:nCalory];
  }
  
  _nSyncPos++;
  [self requestStpData];
}

- (void) storeSyncDownloadStpData:(NSNumber*)nMeasId date:(NSString*)sTime step:(NSNumber*)nSteps dist:(NSNumber*)nDist calory:(NSNumber*)nCalory
{
  dispatch_sync(dispatch_get_main_queue(), ^{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [pApp insertSyncStepsData:nMeasId date:sTime step:nSteps dist:nDist calory:nCalory];
  });
}


//delegate funcs
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
  //_lblMsg.text = error.description;
  if(error != nil) {
    _lblMsg.text = NSLocalizedString(@"APP Server Connection failed!", nil);
    _lblMsg.textColor = [UIColor redColor];
    [self stopSyncProcess];
    AudioServicesPlaySystemSound(1112);
  }
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
  if (data == nil) {
    [_actView stopAnimating];
    _btnSyncData.hidden = NO;
    AudioServicesPlaySystemSound(1112);
    return;
  }
  
  //BOOL bShowProg = YES;
  if(_bSyncGetWgtReqst) {
    _nSyncCurrentPack++;
    [self storeSyncGetStpData:data];
  }
  else {
    /*NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
     sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
     if([sRecv hasPrefix:@"Ready"]) {
     if([self sendWgtData])
     _nSyncCurrentPack++;
     
     _nSyncPos++;
     }
     else {
     [self stopSyncProcess];
     }*/
    [self stopSyncProcess];
  }
  //if(bShowProg)
  //[self performSelectorOnMainThread:@selector(showSyncProgress) withObject:nil waitUntilDone:NO];
}

@end
